/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package eu.fsiebert.polytech.db.mediatheque.front.servlet;

import eu.fsiebert.polytech.db.mediatheque.entity.Adherent;
import eu.fsiebert.polytech.db.mediatheque.entity.Item;
import eu.fsiebert.polytech.db.mediatheque.session.AdherentFacade;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author hocine
 */
public class User extends HttpServlet {

    @EJB
    private AdherentFacade facade;  
    
    
    
    protected void processLogin(HttpServletRequest request, HttpServletResponse response) throws NoSuchAlgorithmException{
        String login         = (String) request.getParameter("login");
        String password  = (String) request.getParameter("password");
        Adherent adherent;
        MessageDigest algo = MessageDigest.getInstance("SHA-1");
        System.out.println("user try to connect with : " + login + " " + password);
        try{
            adherent = facade.getByLoginPassword(login, hash(password, algo));
        } catch(javax.persistence.NoResultException e){
            adherent = null;
        }
        HttpSession session = request.getSession(true);
        if(adherent != null){
            session.setAttribute("user", adherent);
            List<Item> panier = new ArrayList<Item>();
            session.setAttribute("panier", panier);
        }else{
            request.setAttribute("login-error", "login ou mot de passe incorrect");
        }
    }
    
    protected void processLogout(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        session.removeAttribute("user");
    }
    /** 
     * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException, NoSuchAlgorithmException {
        
        //AdherentFacade facade = new AdherentFacade();
        
         //Get the data from user's form
        String action         = (String) request.getParameter("action");
        
        if(action != null){
            if(action.equals("Connexion")){
                this.processLogin(request, response);
            }

            else if(action.equals("Deconnexion")){
                this.processLogout(request, response);
            }
        }
        String redirect  = (String) request.getParameter("redirect");
        if(redirect == null)
            redirect = "index.jsp";

        request.getRequestDispatcher(redirect).include(request, response);

    }
    private String hash(String str, MessageDigest algo) {
        byte[] toHash = str.getBytes();
        byte[] digest = null;
        StringBuilder hashString = new StringBuilder();

        algo.reset();
        algo.update(toHash);
        digest = algo.digest();

        for (int i = 0; i < digest.length; i++) {
            String hex = Integer.toHexString(digest[i]);
            if (hex.length() == 1) {
                hashString.append('0');
                hashString.append(hex.charAt(hex.length() - 1));
            } else {
                hashString.append(hex.substring(hex.length() - 2));
            }
        }
        return hashString.toString();
    }

    // <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
    /** 
     * Handles the HTTP <code>GET</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Handles the HTTP <code>POST</code> method.
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        try {
            processRequest(request, response);
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(User.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

    /** 
     * Returns a short description of the servlet.
     * @return a String containing servlet description
     */
    @Override
    public String getServletInfo() {
        return "Short description";
    }// </editor-fold>
}
